<template>
  <div>
    <!-- 头部 -->
    <van-sticky>
    <van-nav-bar title="购物车" left-text="返回" left-arrow :right-text="editing ? '完成' : '编辑'" @click-right="toggleEditing"
      @click-left="goBack" />
    </van-sticky>
    <!-- 非编辑状态显示数量 -->
    <!-- <span v-show="!editing" class="f999 f12">x {{ item.buyNum }}</span> -->
    <!-- 购物车列表-html部分 -->
    <van-checkbox-group v-model="idList">
      <ul class="goods-list">
        <li class="item" v-for="(item, index) in cartData" :key="index">
          <van-checkbox @click="selectOne" :name="item.cartId" checked-color="red" icon-size="15px"></van-checkbox>
          <div class="left">
            <img :src="item.imgUrl" alt="">
          </div>
          <div class="right">
            <p class="overFlow">{{item.masterName}}</p>
            <p class="overFlow f999" style="margin-left:5px;color: grey;">{{item.slaveName}}</p>
            <p class="money-box">
              <span class="money">￥{{(item.price/100).toFixed(2)}}</span>
              <!-- <span>x2</span> -->
              <!-- 编辑状态 -->
              <van-stepper :name="index" v-show="editing" :value="item.buyNum" async-change
                @plus="updateNum(item, item.buyNum + 1)" @minus="updateNum(item, item.buyNum - 1)" />
  
              <!-- 非编辑状态 -->
              <span v-show="!editing" class="f999 f12">x {{ item.buyNum }}</span>
            </p>
          </div>
        </li>
  
      </ul>
  
      <div style="height: 20px;margin-bottom: 99px;color: #999;" class="flex jc-c aic bg-fff">
        <!-- <div class="middle f12 f999">--已经到底了--</div> -->
      </div>
    </van-checkbox-group>
    <!--  -------结算页面------- -->
  
    
    <van-submit-bar :price="totalMoney" :button-text="editing ? '删除' : '结算'" @submit="submitGoods" style="margin-bottom: 49px;">
      <van-checkbox :value="checkAll" icon-size="15px" @click="selectAll" >
        全选
      </van-checkbox>
  
  
    </van-submit-bar>
    <Footer />
  </div>
</template>

<script>
import request from "@/utils/request";
import { Dialog } from 'vant';
import Footer from'../components/Footer.vue';
export default {
  components: {
            Footer
        },
  data() {
    return {
      // 购物车数据
      idList: [],
      cartData: [],
      editing: false,
      checkAll: false,
    };
  },
  created() {
    this.getCartList();
  },
  computed: {
    totalMoney() {
      // 根据 idList 找到对应的成员
      let selectList = this.cartData.filter(item => this.idList.includes(item.cartId));
      let money = 0;
      selectList.forEach(item => {
        // 单个商品的总价
        let price = item.price * item.buyNum;
        money += price;
      });
      return money;
    },
  },

  methods: {
    // 获取购物车列表
    async getCartList() {
      let res = await request.get("/cart/list");
      console.log(res);
      this.cartData = res.list;
    },

    toggleEditing() {
      this.editing = !this.editing; // 切换状态
    },
    goBack() {
      console.log("触发返回逻辑");
      // 示例逻辑：返回上一页
      this.$router.back();
    },
    // 修改购物车数量 buyNum 最新的值
    updateNum(item, buyNum) {
      let data = {
        cartId: item.cartId,
        buyNum: buyNum
      };
      request.get('/cart/updateNum', { params: data }).then(res => {
        item.buyNum = buyNum;
      }).catch(() => {
        console.log('更新失败');
      });
    },
    // 全选方法
    selectAll() {
      this.checkAll = !this.checkAll;
      if (this.checkAll) {
        this.idList = this.cartData.map(item => item.cartId); // 全选时收集所有 cartId
      } else {
        this.idList = []; // 未选时清空
      }
    },
    // 选中一个
    selectOne() {
      // 全选
      if (this.idList.length === this.cartData.length) {
        this.checkAll = true;
      } else {
        this.checkAll = false;
      }
    },
    // 删除商品
    async onSubmit() {
      if (this.editing) {
        let url = '/cart/del';
        let data = {
          cartId: this.idList
        };
        let res = await request.post(url, data);
        // 留下没选中的商品
        this.cartData = this.cartData.filter(item => !this.idList.includes(item.cartId));
      } else {
        // alert('结算');
      }
    },

    //弹出警示框
    showDialog() {
      Dialog.confirm({
        title: '删除商品',
        message: '确定要删除选中的商品吗？',
      })
        .then(() => {
          // on confirm 
          this.onSubmit();
        })
        .catch(() => {
          // on cancel
        });
    },
    submitGoods() {
      if (this.editing) {
        // 删除商品
        this.showDialog();
      } else {
        // alert('结算');
        // 结算逻辑
        // 1. 先判断是否有选中的商品
        if (this.idList.length === 0) {
          Dialog.alert({
            title: '提示',
            message: '请选择商品',
          });
          return;
        } else {
          // 2. 弹出确认框    
          Dialog.confirm({
            title: '提交订单',
            message: '',
          })
            .then(() => {
              //  创建一个订单，跳转到订单页面
              //  跳转到订单页面
              let data = {
                totalMoney: this.totalMoney,
                cartId: this.idList
              }

              
              // 使用query
              request.post('/preOrder/create', data).then(res => {
                this.$router.push({
                  path: '/order/verify',
                  // path: '/demo',
                  query: {
                    orderData: JSON.stringify(res.result) // 将数组转为JSON字符串
                  }
                });
              })


            }).catch(() => {
              console.log('创建订单失败');
              // });
            })
            .catch(() => {
              // on cancel
            });
        }

      }
    }
  },
};
</script>

<style lang="less" scoped>
@import "cart.less";
</style>